#include "../include/user_list_manger.h"
#include "../include/redis_pool.h"
#include <iostream>
void user_list_manger::add_tcp_connection(const std::string & email,const std::shared_ptr<tcp_connection>  & con)
{
    std::lock_guard<std::shared_mutex> l_g(this->mtx);
    this->local_user_list_map.insert(std::make_pair(email,con));

}

void user_list_manger::remove_tcp_connection(const std::string & email)
{
    {
        std::lock_guard<std::shared_mutex> l_g(this->mtx);
        this->local_user_list_map.erase(email);
    }
    //还要更新redis的信息
    //获取redis信息
    MyRedis * one=redis_pool::get_instance()->get_one_redis();
    if(one==nullptr){
        std::cout<<"有一个连接断开了，我更新redis数据却失败了"<<std::endl;
        return;
    }
    int opt_res=one->hincrby(CHAT_SERVER,this->char_server_field.c_str(),-1);
    if(opt_res==-1){
        std::cout<<"一个连接断开时,当前的redis连接可能失效了"<<std::endl;
        redis_pool::get_instance()->give_back_one_redis(one);
        return;
    }
    //还要更新user_set的用户列表
    if(one->srem(this->user_list_key.c_str(),email.c_str())){
        std::cout<<"成功溢出redis中本服务器的用户set"<<std::endl;
    }
    
    std::cout<<"一个连接断开时,成功更新redis保存的当前chat_server连接数"<<std::endl;
    redis_pool::get_instance()->give_back_one_redis(one);
    return;


    
}

std::shared_ptr<tcp_connection> user_list_manger::find_and_get_con(const std::string &email){
    
    std::shared_ptr<tcp_connection> con;
    mtx.lock_shared();
    if(this->local_user_list_map.count(email)){
        con=this->local_user_list_map[email];
    }else{
        con=nullptr;
    }
    
    mtx.unlock_shared();

    return con;

}

void user_list_manger::update_client_server_cache(const std::string &email, const std::string &ip_port)
{
    this->mtx_client_server_cache.lock();

    this->client_server_cache[email]=ip_port;

    this->mtx_client_server_cache.unlock();

}



std::string  user_list_manger::get_client_server_cache(const std::string &email){
    std::string search_res;
    this->mtx_client_server_cache.lock_shared();

    if(client_server_cache.count(email)){
        search_res=client_server_cache[email];
    }
    this->mtx_client_server_cache.unlock_shared();
    return search_res;

}

void user_list_manger::delete_one_client_server_cache(const std::string &email)
{

    this->mtx_client_server_cache.lock();

    this->client_server_cache.erase(email);

    this->mtx_client_server_cache.unlock();

}





